package com.gitee.base.ldt;

import freemarker.ext.beans.BeansWrapper;
import freemarker.template.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import javax.annotation.PostConstruct;
import java.sql.Date;
import java.sql.Time;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

@Component
public class LocalDateTimeFreeMarkerCfg {
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @PostConstruct
    public void setSharedVariable() throws TemplateModelException {
        freeMarkerConfigurer.getConfiguration().setObjectWrapper(new BeansWrapper(Configuration.VERSION_2_3_31){
            @Override
            public TemplateModel wrap(Object object) throws TemplateModelException {
                if (object instanceof LocalDateTime) {
                    Timestamp timestamp = Timestamp.valueOf((LocalDateTime) object);
                    return new SimpleDate(timestamp);
                }
                if (object instanceof LocalDate) {
                    Date date = Date.valueOf((LocalDate) object);
                    return new SimpleDate(date);
                }
                if (object instanceof LocalTime) {
                    Time time = Time.valueOf((LocalTime) object);
                    return new SimpleDate(time);
                }
                return super.wrap(object);
            }
        });
    }

}
